package cn.yshujia.repository;

import cn.yshujia.domain.entity.Role;
import cn.yshujia.mapper.RoleMapper;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

import java.time.Duration;
import java.util.List;
import java.util.Set;

/**
 * @author YShuJia
 * @create 2025/2/23
 * @description RoleRepository
 */


@Repository
public class RoleRepository {
	
	@Resource
	private RoleMapper mapper;
	
	@Resource
	private RedisTemplate<String, Role> redis;
	
	private final String VO = "role:";
	
	private final String VO_LIST = "role:list";
	
	private final Duration DURATION = Duration.ofDays(3L);
	
	public Role getRole(Long id) {
		Role vo = redis.opsForValue().get(VO + id);
		if (!ObjectUtils.isEmpty(vo)) {
			return vo;
		}
		Role role = mapper.selectById(id);
		redis.opsForValue().set(VO + id, role, DURATION);
		return role;
	}
	
	public List<Role> list() {
		List<Role> list = redis.opsForList().range(VO_LIST, 0L, -1L);
		if (!ObjectUtils.isEmpty(list)) {
			return list;
		}
		list = mapper.selectList(null);
		if (!ObjectUtils.isEmpty(list)) {
			set(list, VO_LIST);
		}
		return list;
	}
	
	@Async ("Task")
	public void set(List<Role> value, String key) {
		redis.opsForList().rightPushAll(key, value);
		redis.expire(key, DURATION);
	}
	
	@Async ("Task")
	public void del() {
		Set<String> keys = redis.keys(VO + "*");
		redis.delete(keys);
	}
}
